package com.linran.structure_algorithm.算法.常用算法.a6_prim;

import java.util.Arrays;

/**
 * 普利姆算法
 *
 * 最小生成树问题
 */
public class PrimAlgorithm {
    public static void main(String[] args) {
        char[] data = {'A', 'B', 'C', 'D', 'E', 'F', 'G'};
        int verx = data.length;
        int[][] weight = new int[][]{
                {10000, 5, 7, 10000, 10000, 10000, 2},
                {5, 10000, 10000, 9, 10000, 10000, 3},
                {7, 10000, 10000, 10000, 8, 10000, 10000},
                {10000, 9, 10000, 10000, 10000, 4, 10000},
                {10000, 10000, 8, 10000, 10000, 5, 4},
                {10000, 10000, 10000, 4, 5, 10000, 6},
                {2, 3, 10000, 10000, 4, 6, 10000}
        };
        MGraph graph = new MGraph(verx);
        MinTree minTree = new MinTree();
        minTree.createGraph(graph, verx, data, weight);
        minTree.showGraph(graph);
        minTree.prim(graph, 1);
    }
}

class MinTree {

    /**
     * 创建图邻矩阵
     *
     * @param graph
     * @param verxs
     * @param data
     * @param weight
     */
    public void createGraph(MGraph graph, int verxs, char[] data, int[][] weight) {
        for (int i = 0; i < verxs; i++) {
            graph.data[i] = data[i];
            for (int j = 0; j < verxs; j++) {
                graph.weight[i][j] = weight[i][j];
            }
        }
    }

    /**
     * 创建最小生成树
     *
     * @param graph
     */
    public void showGraph(MGraph graph) {
        for (int[] ints : graph.weight) {
            System.out.println(Arrays.toString(ints));
        }
    }

    /**
     * 寻找边总和最小解
     *
     * @param graph
     */
    public void prim(MGraph graph, int v) {
        int[] isVisited = new int[graph.verx];
        isVisited[v] = 1;//标记当前节点已访问
        int h1 = -1, h2 = -1;
        for (int k = 1; k < graph.verx; k++) { //边为顶点个数-1
            int minWeight = Integer.MAX_VALUE;
            for (int i = 0; i < graph.verx; i++) {
                for (int j = 0; j < graph.verx; j++) {
                    if (isVisited[i] == 1 && isVisited[j] == 0 && graph.weight[i][j] < minWeight) {
                        minWeight = graph.weight[i][j];
                        h1 = i;
                        h2 = j;
                    }
                }
            }
            isVisited[h2] = 1;
            System.out.println("<" + graph.data[h1] + "," + graph.data[h2] + "> 权值:" + minWeight);
        }
    }
}

class MGraph {
    int verx; //表示图的节点个数
    char[] data; //保存节点数据
    int[][] weight; //邻节矩阵

    public MGraph(int verx) {
        this.verx = verx;
        this.data = new char[verx];
        this.weight = new int[verx][verx];
    }
}